package com.drought.rained.ui.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.os.Build;
import android.support.v4.widget.NestedScrollView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.drought.rained.business.AuthRouterLJ;
import com.drought.rained.business.RouterMapLJ;
import com.drought.rained.cache.UserInfoLJ;
import com.drought.rained.common.ConstantLJ;
import com.drought.rained.rxbus.EventMsgLJ;
import com.drought.rained.rxbus.RxBusLJ;
import com.drought.rained.ui.activity.WebViewActivityLJ;
import com.drought.rained.utils.ToastUtilsLJ;
import com.google.gson.Gson;
import com.drought.rained.R;
import com.drought.rained.LJApplication;
import com.drought.rained.adapter.BannerViewHolderLJ;
import com.drought.rained.base.BaseFragment;
import com.drought.rained.bean.AnnouncementDataLJ;
import com.drought.rained.bean.AuthDataLJ;
import com.drought.rained.bean.CalculateDataLJ;
import com.drought.rained.bean.JsOrderDataLJ;
import com.drought.rained.bean.MoneyProductDataLJ;
import com.drought.rained.bean.TermProductDataLJ;
import com.drought.rained.cache.AcacheLJ;
import com.drought.rained.cache.AcacheKeysLJ;
import com.drought.rained.mvpview.AuthMvpViewLJ;
import com.drought.rained.mvpview.HomeMvpViewLJ;
import com.drought.rained.mvpview.OrderMvpViewLJ;
import com.drought.rained.mvpview.UploadMvpViewLJ;
import com.drought.rained.network.UrlsLJ;
import com.drought.rained.permission.IPermissonLJ;
import com.drought.rained.permission.PermissionLJ;
import com.drought.rained.presenter.AuthPresenterLJ;
import com.drought.rained.presenter.HomePresenterLJ;
import com.drought.rained.presenter.OrderPresenterLJ;
import com.drought.rained.presenter.UploadPresenterLJ;
import com.drought.rained.response.AnnouncementResponseLJ;
import com.drought.rained.response.AuthResponseLJ;
import com.drought.rained.response.BlankResponseLJ;
import com.drought.rained.response.CalculateResponseLJ;
import com.drought.rained.response.CheckOrderQualificationsResponseLJ;
import com.drought.rained.response.CreateOrderResponseLJ;
import com.drought.rained.response.OrderItemResponseLJ;
import com.drought.rained.response.ProductResponseLJ;
import com.drought.rained.response.PullAddressResponseLJ;
import com.drought.rained.rxbus.EventsLJ;
import com.drought.rained.utils.LocationUtilsLJ;
import com.drought.rained.utils.StringUtilsLJ;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

import static com.drought.rained.common.RouterCommandLJ.STATUS_TYPE_KEY;

@SuppressLint("SetTextI18n")
public class LoanFragmentLJ extends BaseFragment implements IPermissonLJ, ViewTreeObserver.OnScrollChangedListener,
        SeekBar.OnSeekBarChangeListener, HomeMvpViewLJ, OrderMvpViewLJ, AuthMvpViewLJ, UploadMvpViewLJ {

    @BindView(R.id.img_loan_header)
    ImageView imgLoanHeader; // 首页头部背景图片
    @BindView(R.id.iv_loan_banner)
    ImageView ivLoanBanner; // Banner占位图
    @BindView(R.id.banner)
    MZBannerView bannerView; // BannerView
    @BindView(R.id.layout_title_bg)
    View layoutTitleBg; // 标题栏背景
    @BindView(R.id.tv_loan_title)
    TextView tvLoanTitle; // 标题
    @BindView(R.id.tv_title_reference)
    TextView tvTitleReference; // 标题参照物
    @BindView(R.id.scroll_view)
    NestedScrollView scrollView;
    @BindView(R.id.tv_loan_money)
    TextView tvLoanMoney; // 产品
    @BindView(R.id.seek_product)
    SeekBar seekProduct;
    @BindView(R.id.tv_product_min)
    TextView tvProductMin;
    @BindView(R.id.tv_product_max)
    TextView tvProductMax;
    @BindView(R.id.tv_loan_term)
    TextView tvLoanTerm; // 期限
    @BindView(R.id.seek_term)
    SeekBar seekTerm;
    @BindView(R.id.tv_term_min)
    TextView tvTermMin;
    @BindView(R.id.tv_term_max)
    TextView tvTermMax;
    @BindView(R.id.layout_detail)
    LinearLayout layoutDetail; // 订单明细布局
    @BindView(R.id.tv_interest)
    TextView tvInterest; // 利息
    @BindView(R.id.tv_member_management_fee)
    TextView tvMemberManagementFee; // 会员管理费
    @BindView(R.id.tv_account_maintenance_fee)
    TextView tvAccountMaintenanceFee; // 账户管理费
    @BindView(R.id.tv_time_out)
    TextView tvTimeOut; // 到期应还
    @BindView(R.id.tv_real_pay)
    TextView tvRealPay; // 实收
    @BindView(R.id.view_loan_data_empty)
    RelativeLayout loanDataEmpty; // 数据有误
    @BindView(R.id.check_agreement)
    CheckBox checkAgreement; // 阅读协议
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.btn_repayment_affirm)
    Button btnRepaymentAffirm;
    @BindView(R.id.rl_bill)
    RelativeLayout rlBill; // 当前账单

    private HomePresenterLJ homePresenter;
    private OrderPresenterLJ orderPresenter;
    private AuthPresenterLJ authPresenter;
    private UploadPresenterLJ uploadPresenter;
    private List<MoneyProductDataLJ> productData; // 数据源
    private List<TermProductDataLJ> termData; // 期限数据

    private String mBorrowMoney; // 借款金额
    private String mPid;
    private CalculateDataLJ mCalculateData; // 当前借款明细
    private String userUuid; // 提单用
    private String addressBookUuid; // 拉取通讯录id
    private int isPerformAnimation; // 是否执行动画 0已执行 1还原动画

    @Override
    public void onFragmentCreated(View rootView) {
        ButterKnife.bind(this, rootView);
        layoutTitleBg.setAlpha(0f);
        boolean license = false;
        if (AcacheLJ.get(LJApplication.getContext()).getAsObject(AcacheKeysLJ.LICENSE) != null) {
            license = (boolean) AcacheLJ.get(LJApplication.getContext()).getAsObject(AcacheKeysLJ.LICENSE);
        }
        checkAgreement.setChecked(license);
        scrollView.getViewTreeObserver().addOnScrollChangedListener(this);
        //设置BannerView 的切换时间间隔
        bannerView.setDelayedTime(5000);
        //设置是否显示Indicator
        bannerView.setIndicatorVisible(true);

        seekProduct.setOnSeekBarChangeListener(this);
        seekTerm.setOnSeekBarChangeListener(this);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onUIReady() {
        homePresenter = new HomePresenterLJ(this);
        orderPresenter = new OrderPresenterLJ(this);
        authPresenter = new AuthPresenterLJ(this);
        uploadPresenter = new UploadPresenterLJ(this);

        RxBusLJ.getInstance().toObservable().map(new Function<Object, EventMsgLJ>() {
            @Override
            public EventMsgLJ apply(Object o) throws Exception {
                return (EventMsgLJ) o;
            }
        }).subscribe(new Consumer<EventMsgLJ>() {
            @Override
            public void accept(EventMsgLJ eventMsg) throws Exception {
                if (EventsLJ.LOGIN_SUCCESS.equals(eventMsg.getMsg())) {
                    homePresenter.getProductData();
//                    homePresenter.getOrderData();
                } else if (EventsLJ.LOGOUT.equals(eventMsg.getMsg())) {
                    homePresenter.getProductData();
                    rlBill.setVisibility(View.GONE);
                    layoutDetail.setVisibility(View.GONE);
                }
            }
        });

        homePresenter.getAnnouncement(); // 获取公告
        homePresenter.getProductData(); // 获取产品
//        if (UserInfoLJ.isLogin()) {
//            homePresenter.getOrderData(); // 获取当前订单
//        }

    }

    @Override
    public int getContentView() {
        return R.layout.fragment_of_loan_layout;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (seekBar == null || productData == null || termData == null) return;
        // 当进度条完成拖动时
        int progress = seekBarCorrection(seekBar);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            seekBar.setProgress(progress, true);
        } else {
            seekBar.setProgress(progress);
        }
        int scale = getSeekBarScale(seekBar); // 单位

        int index = 0;
        if (progress != 0) index = progress / scale;

        switch (seekBar.getId()) {
            case R.id.seek_product:
                String money = productData.get(index).getProdRange();
                if (!money.equals(mBorrowMoney)) {
                    mBorrowMoney = productData.get(index).getProdRange();
                    tvLoanMoney.setText(getStringResource(R.string.money_unit_hint) + " " + StringUtilsLJ.getDotMoneyStr(mBorrowMoney));
                    termData = productData.get(index).getProdDetailDTOList();
                    seekTerm.setProgress(0);
                    fillTerm();
                }
                break;
            case R.id.seek_term:
                String pid = termData.get(index).getPId();
                if (!pid.equals(mPid)) {
                    tvLoanTerm.setText(termData.get(index).getPTerm() + getStringResource(R.string.bill_days_unit));
                    mPid = pid;
                    if (UserInfoLJ.isLogin()) {
                        orderPresenter.getCalculateData(mBorrowMoney, mPid);
                    }
                }
                break;
        }
    }

    @OnClick({R.id.tv_agreement, R.id.rl_bill, R.id.btn_repayment_affirm})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.rl_bill:
                if (UserInfoLJ.isLogin()) {
                    homePresenter.getOrderData(); // 获取当前订单
                }
                break;
            case R.id.tv_agreement:
                checkAgreement.setChecked(true);
                jumpToWebPage();
                break;
            case R.id.btn_repayment_affirm:
                if (!UserInfoLJ.isLogin()) {
                    ARouter.getInstance().build(RouterMapLJ.FACEBOOKLOGIN).navigation();
                    ToastUtilsLJ.showShort(getActivity(), R.string.login_not_login);
                    return;
                }
                if (!checkAgreement.isChecked()) {
                    ToastUtilsLJ.showShort(getActivity(), getStringResource(R.string.register_not_agree));
                    return;
                }
                if (StringUtilsLJ.isEmpty(mBorrowMoney) || StringUtilsLJ.isEmpty(mPid)) {
                    ToastUtilsLJ.showShort(getActivity(), getStringResource(R.string.illegal_params));
                    return;
                }
                orderPresenter.checkOrderQualifications();
                showLoadingView();
                break;
        }
    }

    @Override
    public void onGetDataNext(AnnouncementResponseLJ response) {
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            if (response.hasData()) {
                ivLoanBanner.setVisibility(View.GONE);
                ArrayList<AnnouncementDataLJ> list = response.getData();
                bannerView.setPages(list, new MZHolderCreator<BannerViewHolderLJ>() {
                    @Override
                    public BannerViewHolderLJ createViewHolder() {
                        return new BannerViewHolderLJ();
                    }
                });
                if (list.size() > 1) {
                    bannerView.start();
                } else {
                    bannerView.setCanLoop(false);
                }
            } else {
                ivLoanBanner.setVisibility(View.VISIBLE);
            }
        } else {
            ToastUtilsLJ.showShort(getActivity(), response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(ProductResponseLJ response) {
        dismissLoadingView();
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            if (response.hasData()) {
                loanDataEmpty.setVisibility(View.GONE);
                productData = response.getData();
                // 此处处理一下数据源
                for (int i = 0; i < productData.size(); i++) {
                    MoneyProductDataLJ data = productData.get(i);
                    if (data.getProdDetailDTOList().size() == 1) {
                        TermProductDataLJ term = data.getProdDetailDTOList().get(0);
                        data.getProdDetailDTOList().add(term);
                    }
                }
                if (productData.size() == 1) {
                    MoneyProductDataLJ money = productData.get(0);
                    productData.add(money);
                }
                fillProduct();
            } else {
                loanDataEmpty.setVisibility(View.VISIBLE);
            }
        } else {
            loanDataEmpty.setVisibility(View.VISIBLE);
            ToastUtilsLJ.showShort(getActivity(), response.getMessage());
        }
    }

    private void fillProduct() {
        if (productData == null || productData.size() == 0) {
            homePresenter.getProductData();
            return;
        }
        mBorrowMoney = productData.get(0).getProdRange();
        String min = getStringResource(R.string.money_unit_hint) + " " + StringUtilsLJ.getDotMoneyStr(productData.get(0).getProdRange());
        tvLoanMoney.setText(min);
        tvProductMin.setText(min);
        tvProductMax.setText(getStringResource(R.string.money_unit_hint) + " " + StringUtilsLJ.getDotMoneyStr(productData.get(productData.size() - 1).getProdRange()));
        termData = productData.get(0).getProdDetailDTOList();
        fillTerm();
    }

    private void fillTerm() {
        mPid = termData.get(0).getPId();
        String min = termData.get(0).getPTerm() + getStringResource(R.string.bill_days_unit);
        tvLoanTerm.setText(min);
        tvTermMin.setText(min);
        tvTermMax.setText(termData.get(termData.size() - 1).getPTerm() + getStringResource(R.string.bill_days_unit));
        if (UserInfoLJ.isLogin()) {
            orderPresenter.getCalculateData(mBorrowMoney, mPid);
        }
    }

    @Override
    public void onGetDataNext(CalculateResponseLJ response) {
        dismissLoadingView();
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            if (response.hasData()) {
                loanDataEmpty.setVisibility(View.GONE);
                layoutDetail.setVisibility(View.VISIBLE);
                fillLoanDetail(response.getData());
            } else {
                layoutDetail.setVisibility(View.GONE);
                loanDataEmpty.setVisibility(View.VISIBLE);
            }
        } else {
            loanDataEmpty.setVisibility(View.VISIBLE);
            ToastUtilsLJ.showShort(getActivity(), response.getMessage());
        }
    }

    private void fillLoanDetail(CalculateDataLJ data) {
        mCalculateData = data;
        String repaymentBrowingUnit = getResources().getString(R.string.repayment_browing_unit);
        String moneyUnitHint = getResources().getString(R.string.money_unit_hint);
        tvInterest.setText(String.format(repaymentBrowingUnit, data.getPInterest()));
        tvMemberManagementFee.setText(String.format(repaymentBrowingUnit, data.getPCreditserviceFee()));
        tvAccountMaintenanceFee.setText(String.format(repaymentBrowingUnit, data.getPAccountFee()));
        tvTimeOut.setText(moneyUnitHint + " " + StringUtilsLJ.getDotMoneyStr(data.getExpiryReturned()));
        tvRealPay.setText(moneyUnitHint + " " + StringUtilsLJ.getDotMoneyStr(data.getNeteceipts()));
    }

    @Override
    public void onGetDataNext(OrderItemResponseLJ response) {
        // 首页弹窗
//        if (response.getStatus() == ConstantLJ.HTTP_OK) {
//            if (response.hasData()) {
//                rlBill.setVisibility(View.VISIBLE);
//                OrderItemDataLJ orderItemData = response.getData().get(0);
//                repaymentDialog = new RepaymentDialog(getContext(), R.style.normal_dialog);
//                repaymentDialog.setContent(String.valueOf(orderItemData.getRepayMoney()), orderItemData.getLastPayDate(),
//                        orderItemData.getOrderId(), orderItemData.getOrderStatus(), orderItemData.getProductTerm());
//                repaymentDialog.setStatus(orderItemData.getOrderStatus());
//                if (!orderItemData.isPartialRepaymentMark() &&orderItemData.getOrderStatus() == ConstantLJ.ORDER_STATUS_OVERDUE) {
//                    rolloverAppPresenter.checkCollectStatus();
//                    star = true;
//                } else {
//                    repaymentDialog.setRollove(false);
//                    dialogShow();
//                }
//            } else {
//                rlBill.setVisibility(View.GONE);
//            }
//        } else {
//            rlBill.setVisibility(View.GONE);
//            ToastUtilsLJ.showShort(getActivity(), response.getMessage());
//        }

    }

    @Override
    public void onGetDataNext(CheckOrderQualificationsResponseLJ response) {
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            authPresenter.getAuthStatus();
        } else {
            dismissLoadingView();
            ToastUtilsLJ.showShort(getActivity(), response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(AuthResponseLJ response) {
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            if (response.hasData()) {
                AcacheLJ.get(getActivity()).put(AcacheKeysLJ.AUTH, new Gson().toJson(response.getData(), AuthDataLJ.class));
                // 1未认证，2通过
                if (response.getData().getStatus() == 2) {
                    userUuid = response.getData().getUserUuid();
                    addressBookUuid = response.getData().getAddressBookUuid();
                    PermissionLJ permission = new PermissionLJ(getActivity(), this);
                    permission.uploadLocation();
                } else {
                    dismissLoadingView();
                    AuthRouterLJ.getInstance().jump2FirstNotAuthPager();
                }
            }
        } else {
            dismissLoadingView();
            ToastUtilsLJ.showShort(getActivity(), response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(CreateOrderResponseLJ response) {
        dismissLoadingView();
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            uploadPresenter.pullAddress(addressBookUuid);
            uploadPresenter.uploadLocation(LocationUtilsLJ.getLocation(getActivity()), addressBookUuid);
            btnRepaymentAffirm.setClickable(true);
            ARouter.getInstance().build(RouterMapLJ.STATUS_DISPLAY)
                    .withInt(STATUS_TYPE_KEY, ConstantLJ.STATUS_TYPE_BORROW).navigation();
        }
    }

    @Override
    public void onSuccess(int result) {
        ToastUtilsLJ.showShort(getActivity(), R.string.order_send);
        if (mCalculateData == null) {
            orderPresenter.getCalculateData(mBorrowMoney, mPid);
            showLoadingView();
            return;
        }
        orderPresenter.createOrder(mCalculateData.getApplyAmt(), mPid, userUuid, addressBookUuid);
    }

    @Override
    public void onScrollChanged() {
        int scrollY = scrollView.getScrollY();
        if (scrollY >= 60) {
            if (isPerformAnimation == 0) {
                performAnimation(isPerformAnimation);
            }
        } else {
            if (isPerformAnimation == 1) {
                performAnimation(isPerformAnimation);
            }
        }
    }

    private void performAnimation(int flag) {
        if (tvLoanTitle == null || tvTitleReference == null
                || imgLoanHeader == null || layoutTitleBg == null) return;

        AnimatorSet animatorSet = new AnimatorSet();
        isPerformAnimation = flag == 0 ? 1 : 0; // 表示执行或还原过动画,避免重复执行
        float[] right = flag == 0 ? new float[]{0, tvTitleReference.getLeft() - tvLoanTitle.getLeft()}
                : new float[]{tvTitleReference.getLeft() - tvLoanTitle.getLeft(), 0};
        float[] top = flag == 0 ? new float[]{0, tvTitleReference.getTop() - tvLoanTitle.getTop()}
                : new float[]{tvTitleReference.getTop() - tvLoanTitle.getTop(), 0};
        float[] titleAlpha = flag == 0 ? new float[]{0f, 1f} : new float[]{1f, 0f};
        float[] bgAlpha = flag == 0 ? new float[]{1f, 0f} : new float[]{0f, 1f};
        float[] scaleX = flag == 0 ? new float[]{1f, 1.5f} : new float[]{1.5f, 1f};
        float[] scaleY = flag == 0 ? new float[]{1f, 1.5f} : new float[]{1.5f, 1f};
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(tvLoanTitle, ConstantLJ.PROPERTY_TRANSLATION_X, right).setDuration(400),
                ObjectAnimator.ofFloat(tvLoanTitle, ConstantLJ.PROPERTY_TRANSLATION_Y, top).setDuration(400),
                ObjectAnimator.ofFloat(layoutTitleBg, ConstantLJ.PROPERTY_ALPHA, titleAlpha).setDuration(800),
                ObjectAnimator.ofFloat(imgLoanHeader, ConstantLJ.PROPERTY_ALPHA, bgAlpha).setDuration(800),
                ObjectAnimator.ofFloat(imgLoanHeader, ConstantLJ.PROPERTY_SCALE_X, scaleX).setDuration(800),
                ObjectAnimator.ofFloat(imgLoanHeader, ConstantLJ.PROPERTY_SCALE_Y, scaleY).setDuration(800)
        );
        animatorSet.start();
    }

    private int seekBarCorrection(SeekBar seekBar) {
        int scale = getSeekBarScale(seekBar);
        int current = seekBar.getProgress() / scale;
        int remainder = seekBar.getProgress() % scale;
        int left = current * scale;
        int right = left + scale;
        int b = 100 % scale;
        if (right + b == 100) right = 100;
        if (left + b == 100) return 100;
        return remainder < scale / 2 ? left : right;
    }

    private int getSeekBarScale(SeekBar seekBar) {
        int node = 0;
        switch (seekBar.getId()) {
            case R.id.seek_product:
                node = productData.size() - 1;
                break;
            case R.id.seek_term:
                node = termData.size() - 1;
                break;
        }
        int scale = 100 / node;
        return scale;
    }

    private void jumpToWebPage() {
        if (mCalculateData == null || StringUtilsLJ.isEmpty(mBorrowMoney)) {
            orderPresenter.getCalculateData(mBorrowMoney, mPid);
            showLoadingView();
            return;
        }

        JsOrderDataLJ orderData = new JsOrderDataLJ();
        orderData.setBorrowMoney(mBorrowMoney);
        orderData.setBorrowDay(mCalculateData.getPTerm());
        orderData.setToken(UserInfoLJ.getToken());
        ARouter.getInstance()
                .build(RouterMapLJ.WEB_VIEW_PAGE)
                .withString(WebViewActivityLJ.PARAMS_URL, UrlsLJ.REGISTER_CONTRACT_URL)
                .withSerializable(WebViewActivityLJ.PARAMS_ORDER_DATA, orderData)
                .navigation();
    }

    @Override
    public void onGetDataError(Throwable throwable) {
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // 当进度条开始拖动时
    }

    @Override
    public void onGetDataNext(PullAddressResponseLJ response) {

    }

    @Override
    public void onGetDataNext(BlankResponseLJ response) {

    }
}
